<template>
  <div class="teacher-container">
    <div class="common-layout">
      <el-container class="layout-container">

        <el-aside class="sidebar">
          <div class="sidebar-content">
            <h5 class="sidebar-title">
              <div style="margin-left:20px;display:flex;align-items: center;float:left;vertical-align: middle;height:100%">
                <a :href="'/#/lession?courseid='+courseid+'&name='+name"><el-icon><Back /></el-icon></a>&nbsp;
              </div>&nbsp;
              {{name}}

            </h5>

            <el-menu
                default-active="3"
                class="el-menu-vertical-demo"
                background-color="#f8fafc"
                active-text-color="#4f46e5"
            >

              <el-menu-item index="1" class="menu-item">
                <a :href="'/#/classroom?courseid='+courseid+'&lessionid='+lessionid+'&name='+name">  <el-icon><Document /></el-icon>
                  <span>Material</span></a>
              </el-menu-item>
              <el-menu-item index="2" class="menu-item">
                <a :href="'/#/classroomaudio?courseid='+courseid+'&lessionid='+lessionid+'&name='+name">  <el-icon><VideoPlay /></el-icon>
                  <span>Recoding</span></a>
              </el-menu-item>
              <el-menu-item index="3" class="menu-item">
                <a :href="'/#/classroomscript?courseid='+courseid+'&lessionid='+lessionid+'&name='+name"><el-icon><Service /></el-icon>
                  <span>transcript</span></a>
              </el-menu-item>
            </el-menu>
          </div>

        </el-aside>

        <!-- Main Content -->
        <el-main class="main-content">
          <el-row>
            <div class="page-header">
              <!--            <el-col :span="24" class="topdiv">-->
              <!--              <el-button :icon="Upload" type="primary" @click="showdialog()">upload</el-button>-->
              <!--            </el-col>-->
            </div>
            <el-col :span="24">

              <div class="course-list">

                    <div class="content" style="padding-left:40px;box-shadow: 0px 2px 2px -2px gray;width:100%;" v-show="summary.isShow">
                      <div class="content-panel">
                        <div class="content">
                            <h3>Summary</h3>
                        </div>
                      </div>
                      <div class="content-panel">
                        <div class="content">
                          {{summary.ywContent }}
                        </div>
                      </div>
                      <div class="content-panel">
                        <div class="content">
                          {{summary.zwContent }}
                        </div>
                      </div>
                    </div>




                <div v-for="item in lessionfiledata.list">
                  <div class="content-panel" >
                    <div class="content">
                      <el-icon><Document /></el-icon>{{item.name}}
                    </div>
                    <div class="button">
                      <el-button type="success" :icon="Download" circle @click="doDownload(item.filepath,item.filename)"></el-button>
                      <!-- <el-button type="primary" :icon="SetUp" circle/>     -->
                    </div>
                  </div>
                  <div class="content-panel" v-if="item.lessionTransaudio">
                    <div class="content">
                      <video :src="serverurl+item.lessionTransaudio.filepath" width="640" height="80" controls style="margin: auto;" >您当前浏览器不支持HTMT5视频播放</video>
                    </div>
                  </div>

                  <div class="content-panel" v-for="scriptitem in item.list">
                    <div class="content" style="padding-left:40px;box-shadow: 0px 2px 2px -2px gray;width:100%;">
                      <div class="content-panel">
                        <div class="content">
                          {{scriptitem.createtime}}
                        </div>
                      </div>
                      <div class="content-panel">
                        <div class="content">
                          {{scriptitem.encontent}}
                        </div>
                        <!--                      <div class="button" style="min-width:170px;align-self: center;">-->
                        <!--                        {{scriptitem.createtime}}-->
                        <!--                      </div>-->
                      </div>
                      <div class="content-panel">
                        <div class="content">
                          {{scriptitem.content}}
                        </div>
                        <!--                      <div class="button" style="min-width:170px;align-self: center;">-->
                        <!--                        {{scriptitem.createtime}}-->
                        <!--                      </div>-->
                      </div>
                    </div>
                    <div class="button">
                      <el-button type="primary" :icon="Edit" circle @click="doEdit(scriptitem)" v-if="lessionfiledata.isMyCourse"/>
                    </div>
                  </div>
                </div>

              </div>

              <div v-for="(message, index) in messages" :key="index" class="message" :class="message.sender">
                  <div class="bubble">{{ message.text }}</div>
              </div>

              <!--              <div class="course-list">-->
              <!--                <div-->
              <!--                    class="course-card"-->
              <!--                    v-for="item in lessionfiledata.list"-->
              <!--                    :key="item.id"-->
              <!--                >-->
              <!--                  <div class="course-info">-->
              <!--                    <h3 class="course-name">{{item.filename}}</h3>                 -->
              <!--                  </div>-->
              <!--                  <div class="course-actions">-->
              <!--                    <el-tooltip content="View Lessons" placement="top">-->
              <!--                      <el-button-->
              <!--                          type="success"-->
              <!--                          :icon="Download"-->
              <!--                          circle-->
              <!--                          @click="doDownload(item.filepath,item.filename)"-->
              <!--                          class="action-btn"-->
              <!--                      />-->
              <!--                    </el-tooltip>-->
              <!--                  </div>-->


              <!--                  <div class="content-panel" v-for="scriptitem in item.list">-->
              <!--                    <div class="content" style="padding-left:40px;box-shadow: 0px 2px 2px -2px gray;width:100%;">-->
              <!--                      <div class="content-panel">-->
              <!--                        <div class="content">-->
              <!--                          {{scriptitem.encontent}}-->
              <!--                        </div>-->
              <!--                        <div class="button" style="min-width:170px;align-self: center;">-->
              <!--                          {{scriptitem.createtime}}-->
              <!--                        </div>-->
              <!--                      </div>-->
              <!--                      <div class="content-panel">-->
              <!--                        <div class="content">-->
              <!--                          {{scriptitem.content}}-->
              <!--                        </div>-->
              <!--                        <div class="button" style="min-width:170px;align-self: center;">-->
              <!--                          {{scriptitem.createtime}}-->
              <!--                        </div>-->
              <!--                      </div>-->
              <!--                    </div>-->
              <!--                    <div class="button">-->
              <!--                      <el-button type="primary" :icon="Edit" circle @click="doEdit(scriptitem)" v-if="lessionfiledata.isMyCourse"/>-->
              <!--                    </div>-->
              <!--                  </div>-->



              <!--                </div>-->
              <!--              </div>-->


            </el-col>
          </el-row>

        </el-main>
      </el-container>
    </div>


    <el-dialog v-model="dialogFormVisible.visible" title="save&edit" width="500">
      <el-form>
        <el-form-item label="name" :label-width="formLabelWidth">
          <el-input v-model="onelessiontranscript.id" type="hidden"/>
          <el-input v-model="onelessiontranscript.content" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible.visible = false">Cancel</el-button>
          <el-button type="primary" @click="doSubmit()">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">

//import TopHeader from '../../components/TopHeader.vue' // 引用Header组件
//import TopBottom from '../../components/TopBottom.vue' // 引用Header组件
import {
  Download,
  Delete,
  Edit,
  Message,
  Search,
  SetUp, Upload,
} from '@element-plus/icons-vue'
import { reactive,ref,onMounted,toRaw} from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { uploadImage,download,isMyCourse } from '../../api/course.ts'
import { getMyLessionTransfileList,deleteLessionTransfile } from '../../api/lessiontransfile.ts'
import { saveLessionTranscriptmut,saveSummary,getSummary} from '../../api/lessiontranscriptmut.ts'


const env = import.meta.env
const serverurl:string = env['VITE_APP_BASE_API']
const route = useRoute()
const currentRoute = useRouter()
const courseid = route.query.courseid
const lessionid = route.query.lessionid
const name = route.query.name
const upload = ref<UploadInstance>()
const dialogFormVisible = reactive({
  visible:false
})
const formLabelWidth = '140px'

const summary = reactive({
  ywContent:'',
  zwContent:'',
  isShow: false
})

const onelessiontranscript = reactive({
  id:null,
  content:''
})
const encontent = reactive({
  content:''
})
//lessionfile列表
const lessionfiledata = reactive({
  list:[],
  isMyCourse:false
})
var messages = reactive([])
onMounted(() => {
  loaddata();
})
function loaddata()
{
  getMyLessionTransfileList({"lessionid":lessionid}).then((res) => {
    if (res.code == 200)
    {
      lessionfiledata.list = res.data;
      // for(let item of lessionfiledata.list){
      //   for(let scriptitem of item.list){
      //     encontent.content += scriptitem.encontent;
      //   }
      // }
      // console.log("获取到的英文段落：",encontent.content);
      //  sendMessage(encontent.content+"请对以上英文段落分别用英文和繁体中文进行总结，要求语句简约且通顺。英文总结和繁体中文总结间要换行",15)
    }
  })
  getSummary({"lessionid":lessionid}).then((res) => {
    if (res.code == 200 && res.data)
    {
      summary.ywContent = res.data.ywContent;
      summary.zwContent = res.data.zwContent;
      summary.isShow = true;
    }
  })
  isMyCourse({"courseid":courseid}).then((res) => {
    if (res.code == 200)
    {
      lessionfiledata.isMyCourse = res.data;
    }
  })
}

function sendMessage(encontent,lessionid){
  let eventSource = null;
  if (!encontent) return
  // 只有当eventSource不存在时才创建新的EventSource连接
  if (!eventSource) {
    // messages.push({ text: encontent, sender: 'user' });
    messages.push({ text: "", sender: 'ai' });
    // 创建新的EventSource连接
    eventSource = new EventSource(serverurl+'/chat?content=' + encontent);
    //设置消息接收的回调函数
    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      messages[messages.length - 1].text += data.result;
    };
    // 可选：监听错误事件，以便在出现问题时能够重新连接或处理错误
    eventSource.onerror = (event) => {
      console.error("EventSource failed:", event);
                // 获取原始数组
const rawArray = toRaw(messages);

const regex = /英文总结：\s*(.+?)\s*繁体中文总结：\s*(.+)/;
const matches = rawArray[0].text.match(regex);


// const url = serverurl+"/summary/save"
 const params = {"lessionid":lessionid,"ywContent":matches[1],"zwContent":matches[2]};


 saveSummary(params).then((res) => {
        if (res.code == 200)
        {
          console.log("保存成功");
        }
    })
      eventSource.close(); // 关闭出错的连接
      eventSource = null; // 重置eventSource变量，允许重建连接
    };
  }
}

function doEdit(item)
{
  dialogFormVisible.visible = true
  onelessiontranscript.id=item.id
  onelessiontranscript.content=item.content
}
function doSubmit()
{
  dialogFormVisible.visible = false
  saveLessionTranscriptmut(onelessiontranscript).then((res) => {
    if (res.code == 200)
    {
      //更新下视图数据
      loaddata();
    }
  })
}

function doDelete(id)
{
  deleteLessionTransfile({"id":id}).then((res) => {
    if (res.code == 200)
    {
      //更新下视图数据
      loaddata();
    }
  })
}
function doDownload(filepath,filename)
{
  download({"filepath":filepath}).then((res) => {
    downloadLink(res,filename);
  })

}

function downloadLink(data, title) {
  var elink = document.createElement("a");
  elink.download = title;
  elink.style.display = "none";
  var blob = new Blob([data]);
  elink.href = window.URL.createObjectURL(blob);
  document.body.appendChild(elink);
  elink.click();
  document.body.removeChild(elink);
}

</script>
<style lang="less" scoped>
.teacher-container {
  height: 100vh;
  background-color: #f8fafc;
}

.layout-container {
  height: 100%;
}

.sidebar {
  width: 220px !important;
  background-color: #f8fafc;
  border-right: 1px solid #e2e8f0;

  .sidebar-content {
    padding: 20px 0;

    .sidebar-title {
      color: #64748b;
      font-size: 16px;
      font-weight: 600;
      padding: 0 20px 15px;
      margin: 0;
      border-bottom: 1px solid #e2e8f0;
    }
  }

  .menu-item {
    margin: 5px 10px;
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      background-color: #eef2ff !important;
      color: #4f46e5 !important;
    }

    &.is-active {
      background-color: #eef2ff !important;
      color: #4f46e5 !important;
      font-weight: 500;
    }
  }
}

.main-content {
  padding: 30px !important;
  background-color: white;
  border-radius: 12px 0 0 0;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.05);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;

  .page-title {
    color: #1e293b;
    font-size: 24px;
    margin: 0;
  }

  .add-course-btn {
    background-color: #4f46e5;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(79, 70, 229, 0.2);
    transition: all 0.3s ease;

    &:hover {
      background-color: #4338ca;
      transform: translateY(-2px);
    }

    .el-icon {
      margin-right: 8px;
    }
  }
}

.course-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
}

.course-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #f1f5f9;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-color: #e0e7ff;
  }

  .course-info {
    .course-name {
      font-size: 16px;
      font-weight: 600;
      color: #1e293b;
      margin: 0 0 5px 0;
    }

    .course-year {
      font-size: 13px;
      color: #64748b;
      background-color: #f1f5f9;
      padding: 3px 8px;
      border-radius: 4px;
    }
  }

  .course-actions {
    display: flex;
    gap: 10px;

    .action-btn {
      transition: all 0.2s ease;

      &:hover {
        transform: scale(1.1);
      }
    }
  }
}

.course-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    border-bottom: 1px solid #f1f5f9;
    padding: 20px;
    margin-right: 0;

    .el-dialog__title {
      font-weight: 600;
      color: #1e293b;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  //.dialog-input,
  .dialog-select {
    width: 100%;

    :deep(.el-input__inner) {
      border-radius: 8px;
      border: 1px solid #e2e8f0;
      height: 40px;

      &:focus {
        border-color: #4f46e5;
        box-shadow: 0 0 0 1px rgba(79, 70, 229, 0.2);
      }
    }
  }

  .status-radio {
    :deep(.el-radio__inner) {
      border-color: #cbd5e1;
    }

    :deep(.el-radio__input.is-checked .el-radio__inner) {
      background-color: #4f46e5;
      border-color: #4f46e5;
    }

    :deep(.el-radio__label) {
      color: #475569;
    }
  }

  .upload-btn {
    background-color: #f1f5f9;
    border: none;
    color: #4f46e5;
    border-radius: 8px;

    &:hover {
      background-color: #e0e7ff;
    }

    .el-icon {
      margin-right: 8px;
    }
  }

  .image-preview {
    margin-top: 15px;

    img {
      width: 100px;
      height: 100px;
      object-fit: cover;
      border-radius: 8px;
      border: 1px solid #e2e8f0;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;

    .cancel-btn {
      border-radius: 8px;
      border: 1px solid #e2e8f0;

      &:hover {
        color: #4f46e5;
        border-color: #c7d2fe;
      }
    }

    .confirm-btn {
      background-color: #4f46e5;
      border: none;
      border-radius: 8px;

      &:hover {
        background-color: #4338ca;
      }
    }
  }
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto !important;
    border-right: none;
    border-bottom: 1px solid #e2e8f0;
  }

  .main-content {
    padding: 20px !important;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .course-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;

    .course-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .course-dialog {
    width: 90% !important;
  }
}

.content-panel {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between; /* 左右内容对齐 */
  width: 100%; /* 根据需要调整宽度 */
  padding-top: 10px; /* 根据需要调整内边距 */
  color: rgba(0, 0, 0, .85);
}

.message {
  margin: 10px 0;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.bubble {
  max-width: 100%;
  padding: 12px 16px;
  border-radius: 15px;
  word-break: break-word;
}

.user .bubble {
  background-color: #007bff;
  color: white;
}

.ai .bubble {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
}


/* 或者根据深色模式动态调整 */
@media (prefers-color-scheme: dark) {
  .ai .bubble {
    color: #000000 !important; /* 黑色 */
    background-color: #ffffff;
    border: 1px solid #e0e0e0;
  }
}

</style>
